package org.luxor.generator.config;

import org.luxor.commons.jdbc.plugin.dynamic.properties.DataSourceProperty;
import org.luxor.generator.constant.DateSourceType;
import org.luxor.generator.dao.*;
import org.luxor.generator.service.SysDataSourceService;
import org.luxor.generator.utils.RRException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.util.Assert;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Optional;


/**
 * 全局配置
 *
 * @author Mark sunlightcs@gmail.com
 */
@Configuration
@EnableConfigurationProperties({GeneratorPropertie.class, DataSourceProperty.class})
public class GeneratorAutoConfig implements WebMvcConfigurer {

    @Resource
    private MysqlGeneratorDao mysqlGeneratorDao;
    @Resource
    private OracleGeneratorDao oracleGeneratorDao;
    @Resource
    private SqlServerGeneratorDao sqlServerGeneratorDao;
    @Resource
    private PostgreSqlGeneratorDao postgreSQLGeneratorDao;

    @Value("${spring.datasource.driver-class-name:}")
    private String driverClassName;

    @Bean
    @Primary
    public GeneratorDao getGeneratorDao() {
        Optional<DateSourceType> databaseType = Arrays.stream(DateSourceType.values()).filter(
                el -> driverClassName.indexOf(el.name()) != -1).findFirst();

        if (DateSourceType.mysql.equals(databaseType.get())) {
            return mysqlGeneratorDao;
        } else if (DateSourceType.oracle.equals(databaseType)) {
            return oracleGeneratorDao;
        } else if (DateSourceType.sqlserver.equals(databaseType)) {
            return sqlServerGeneratorDao;
        } else if (DateSourceType.postgresql.equals(databaseType)) {
            return postgreSQLGeneratorDao;
        } else {
            throw new RRException("不支持当前数据库：" + databaseType);
        }
    }

    @Bean
    public ServletListenerRegistrationBean listenerRegist(SysDataSourceService sysDataSourceService) {
        Assert.notNull(sysDataSourceService,"sysDataSourceService is null");

        ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean();
        srb.setListener(sysDataSourceService);
        return srb;
    }
}
